<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 通用工具栏 -->
      <PageTools>
        <!-- 左侧插槽 -->
        <template #left>共 {{ total }} 条记录</template>
        <!-- 右侧默认插槽 -->
        <template>
          <el-button
            v-check="'POINT-USER-IMPORT'"
            type="success"
            size="small"
            icon="el-icon-upload2"
            @click="$router.push('/import?type=employee')"
          >
            excel 导入
          </el-button>
          <el-button
            v-check="'POINT-USER-EXPORT'"
            type="danger"
            size="small"
            icon="el-icon-download"
            :loading="downloadLoading"
            @click="exportExcel"
          >
            excel 导出
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-circle-plus-outline"
            @click="showDialog = true"
          >
            新增员工
          </el-button>
        </template>
      </PageTools>
      <!-- 员工表格 -->
      <el-card>
        <el-table v-loading="loading" border :data="list" stripe>
          <el-table-column label="序号" sortable type="index" :index="indexMethod" width="100" align="center" />
          <el-table-column label="姓名" sortable prop="username" align="center" />
          <el-table-column label="头像" align="center" width="100">
            <template v-slot="{ row }">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                width="80"
                height="80"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%"
                @click="show2Code(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" align="center" />
          <el-table-column
            label="聘用形式"
            sortable
            prop="formOfEmployment"
            align="center"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable prop="departmentName" align="center" />
          <el-table-column
            label="入职时间"
            sortable
            align="center"
          >
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable align="center">
            <template v-slot="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" sortable width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next, jumper"
            :total="total"
            :page-size="pagesize"
            :current-page="page"
            background
            @current-change="changeFn"
          />
        </el-row>
        <!-- 添加弹框 -->
        <AddEmployee :show-dialog.sync="showDialog" @updateList="updateList" />
      </el-card>
      <!-- 查看头像二维码弹框 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog" width="40%">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色弹框 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import AddEmployee from './components/AddEmployee'
import moment from 'moment'
import Qrcode from 'qrcode'
import AssignRole from './components/AssignRole'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [], // 页码对应员工列表
      page: 1, // 页码
      pagesize: 10, // 每页条数
      total: 0, // 总条数
      loading: false,
      hireType: employeeEnum.hireType, // 聘用形式
      showDialog: false,
      downloadLoading: false, // 导出Excel按钮
      showCodeDialog: false, // 二维码弹框
      showRoleDialog: false, // 分配角色弹框
      userId: '' // 点击的当前员工的id
    }
  },
  created() {
    this.getEmployeeList() // 获取员工列表
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page, this.pagesize)
      this.list = rows
      this.total = total
      this.loading = false
    },
    // 页码改变事件
    changeFn(currentPage) {
      // 改变页码参数, 发送请求获取对应页数列表
      this.page = currentPage
      this.getEmployeeList()
    },
    // 自定义序号
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 聘用形式格式化
    formatEmployment(row, column, cellValue, index) {
      try {
        return this.hireType.find(item => item.id === +cellValue).value
      } catch {
        return ''
      }
    },
    // 删除员工
    async del(id) {
      try {
        await this.$confirm('此操作将删除该员工, 是否继续?', '提示', { type: 'warning' })
      } catch {
        return
      }
      await delEmployee(id)
      this.$message.success('删除成功')
      // 如果删除当页最后一条, 更新页码
      if (this.list.length === 1) this.page--
      // 重新渲染
      this.getEmployeeList()
    },
    // 新增员工后更新列表
    updateList() {
      this.total++
      this.page = Math.ceil(this.total / this.pagesize)
      this.getEmployeeList()
    },
    // 导出员工Excel文件
    exportExcel() {
      this.downloadLoading = true
      // 异步导入方式, 得到的是primose, 参数excel就是要导入的对象
      import('@/utils/Export2Excel').then(async excel => {
        const userRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '入职日期': 'timeOfEntry',
          '转正日期': 'correctionTime',
          '部门': 'departmentName'
        }
        // 表头
        const tHeader = Object.keys(userRelations)
        // 获取全部员工列表数据
        const { rows } = await getEmployeeList(1, 1000)
        // 写入Excel的数据 [[], [], ...] 需要转换成数组包数组, 里面对应是各个字段的数据
        const tData = rows.map(item => Object.keys(userRelations).map(k => {
          if (k === '入职日期' || k === '转正日期') {
            // 如果有日期, 转换格式
            let time = item[userRelations[k]]
            if (time) time = moment(time).format('YYYY/MM/DD')
            return time
          } else { // 如果其他需要项转换, 接着判断即可 item[userRelations[k]]就是那一项的值
            return item[userRelations[k]]
          }
        }))
        // console.log(tData)
        // 复杂表头导出配置
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: tHeader,
          data: tData,
          multiHeader, // 复杂表头
          merges, // 表头合并信息
          filename: '员工数据', // 导出的文件名
          autoWidth: true, // excel的列是否自动设置宽度
          bookType: 'xlsx' // 后缀名
        })
        this.downloadLoading = false
      })
    },
    // 二维码
    async show2Code(photo) {
      this.showCodeDialog = true
      await this.$nextTick()
      Qrcode.toCanvas(this.$refs.myCanvas, photo)
    },
    // 点击分配角色
    assign(id) {
      this.userId = id // 保存当前点击员工id, 传递给分配组件
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
